﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WFNetLib;
using System.IO.Ports;
using System.Windows.Forms;
using System.Diagnostics;
using WFNetLib.PacketProc;
using System.Threading;

namespace 生命体征测试仪
{
    public partial class formMedical : formBase
    {
        private void tabXueTang_Enter(object sender, EventArgs e)
        {
            leftTime = ExitTime;
            if(SysConfig.XPCom!=null)
                CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01);
        }        
        private void tabXueTang_Leave(object sender, EventArgs e)
        {
            leftTime = ExitTime;
        }
        void ReadXueTang(int x)
        {
            leftTime = ExitTime;
            if (SysConfig.XPCom == null || SysConfig.XueTangCom == null)
            {
                XueTangResult.Text = "血糖仪设置有误";
                return;
            }
            XueTangResult.Text = "请稍等....";
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x00) == null)
            {
                XueTangResult.Text = "控制器打开血糖仪失败，请检查连线";
                return;
            }
            Thread.Sleep(5000);
            if (XueTangComProc(0x01, 0, null) == null)
            {
                XueTangResult.Text = "与血糖仪建立连线失败，请检查连线";
                if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
                {
                    XueTangResult.Text = "控制器关闭血糖仪失败，请检查连线";
                    return;
                }
                return;
            }
            BeneCheckPacket xt;
            xt = XueTangComProc(0x40, 0, null);
            if (xt == null)
            {
                XueTangResult.Text = "与血糖仪建立连线失败，请检查连线";
            }
            else
            {
                ushort n = BytesOP.MakeShort(xt.Data[1], xt.Data[0]);
                if (n == 0)
                {
                    XueTangResult.Text = "血糖仪中没有血糖测量数据";
                }
                else
                {
                    xt = XueTangComProc(0x41, 0, new byte[] { BytesOP.GetLowByte(n), BytesOP.GetHighByte(n), BytesOP.GetLowByte(n), BytesOP.GetHighByte(n) });
                    if (xt == null)
                    {
                        XueTangResult.Text = "血糖仪中血糖测量数据读取失败";
                    }
                    else
                    {
                        bChange = true;
                        if(x==0)
                        {
                            MedicalResult.XueTang1 = BytesOP.MakeShort(xt.Data[8], xt.Data[7]) / 18.0f;

                            XueTangResult.Text = "餐前血糖测量数据为： " + MedicalResult.XueTang1.ToString() + " mmol/L   ";
                        }
                        else
                        {
                            MedicalResult.XueTang2 = BytesOP.MakeShort(xt.Data[8], xt.Data[7]) / 18.0f;

                            XueTangResult.Text = "餐后血糖测量数据为： " + MedicalResult.XueTang1.ToString() + " mmol/L   ";
                        }
                    }
                }
            }
            lXueTang.Text = "读取完成";
            xt = XueTangComProc(0x20, 0x0001, null);
            if (xt == null)
            {
                lXueTang.Text += "-------清除历史数据失败";
            }
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
            {
                XueTangResult.Text = "与血糖仪建立连线失败，请检查连线";
                return;
            }
        }
        private void btXueTangRead2_Click(object sender, EventArgs e)
        {
            ReadXueTang(1);
        } 
        private void btXueTangRead_Click(object sender, EventArgs e)
        {
            ReadXueTang(0);
            //MedicalResult.XueTang.dt = new DateTime(2000+xt.Data[2], xt.Data[3], xt.Data[4], xt.Data[5], xt.Data[6],0);
            
        }
        private void btNiaoSuanRead_Click(object sender, EventArgs e)
        {
            leftTime = ExitTime;
            if (SysConfig.XPCom == null || SysConfig.XueTangCom == null)
            {
                lNiaoSuan.Text = "血糖仪设置有误";
                return;
            }
            lNiaoSuan.Text = "请稍等....";
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x00) == null)
            {
                XueNiaoSuanResult.Text = "控制器打开血糖仪失败，请检查连线";
                return;
            }
            Thread.Sleep(5000);
            if (XueTangComProc(0x01, 0, null) == null)
            {
                XueNiaoSuanResult.Text = "与血糖仪建立连线失败，请检查连线";
                if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
                {
                    XueNiaoSuanResult.Text = "控制器关闭血糖仪失败，请检查连线";
                    return;
                }
                return;
            }
            BeneCheckPacket xt;// = XueTangComProc(0x30, 0, null);
            //             if (xt == null)
            //             {
            //                 XueTangResult.Text = "与血糖仪建立连线失败，请检查连线";
            //                 return;
            //             }
            //             byte func = BytesOP.GetLowByte(xt.Header.Param);

            //             if (BytesOP.GetBit(func, 1))//血尿酸
            //             {
            xt = XueTangComProc(0x50, 0, null);
            if (xt == null)
            {
                XueNiaoSuanResult.Text = "与血糖仪建立连线失败，请检查连线";
            }
            else
            {
                ushort n = BytesOP.MakeShort(xt.Data[1], xt.Data[0]);
                if (n == 0)
                {
                    XueNiaoSuanResult.Text = "血糖仪中没有血尿酸测量数据";
                }
                else
                {
                    xt = XueTangComProc(0x51, 0, new byte[] { BytesOP.GetLowByte(n), BytesOP.GetHighByte(n), BytesOP.GetLowByte(n), BytesOP.GetHighByte(n) });
                    if (xt == null)
                    {
                        XueNiaoSuanResult.Text = "血糖仪中血尿酸测量数据读取失败";
                    }
                    else
                    {
                        MedicalResult.NiaoSuan = BytesOP.MakeShort(xt.Data[8], xt.Data[7]) * 100 / 16.81f;
                        bChange = true;
                        XueNiaoSuanResult.Text = "血尿酸测量数据为： " + MedicalResult.NiaoSuan.ToString() + " umol/L   ";
                    }
                }
            }
            //}            
            lNiaoSuan.Text = "读取完成";
            xt = XueTangComProc(0x20, 0x0002, null);
            if (xt == null)
            {
                lNiaoSuan.Text += "-------清除历史数据失败";
            }
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
            {
                XueNiaoSuanResult.Text = "控制器关闭血糖仪失败，请检查连线";
                return;
            }
        }

        private void btDanGuChunRead_Click(object sender, EventArgs e)
        {
            leftTime = ExitTime;
            if (SysConfig.XPCom == null || SysConfig.XueTangCom == null)
            {
                lDanGuChun.Text = "血糖仪设置有误";
                return;
            }
            lDanGuChun.Text = "请稍等....";
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x00) == null)
            {
                DanGuChunResult.Text = "控制器打开血糖仪失败，请检查连线";
                return;
            }
            Thread.Sleep(5000);
            if (XueTangComProc(0x01, 0, null) == null)
            {
                DanGuChunResult.Text = "与血糖仪建立连线失败，请检查连线";
                if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
                {
                    DanGuChunResult.Text = "控制器关闭血糖仪失败，请检查连线";
                    return;
                }
                return;
            }
            BeneCheckPacket xt;// = XueTangComProc(0x30, 0, null);
            //             if (xt == null)
            //             {
            //                 XueTangResult.Text = "与血糖仪建立连线失败，请检查连线";
            //                 return;
            //             }
            //             byte func = BytesOP.GetLowByte(xt.Header.Param);

            //             if (BytesOP.GetBit(func, 2))//胆固醇
            //             {
            xt = XueTangComProc(0x60, 0, null);
            if (xt == null)
            {
                DanGuChunResult.Text = "与血糖仪建立连线失败，请检查连线";
            }
            else
            {
                ushort n = BytesOP.MakeShort(xt.Data[1], xt.Data[0]);
                if (n == 0)
                {
                    DanGuChunResult.Text = "血糖仪中没有胆固醇测量数据";
                }
                else
                {
                    xt = XueTangComProc(0x61, 0, new byte[] { BytesOP.GetLowByte(n), BytesOP.GetHighByte(n), BytesOP.GetLowByte(n), BytesOP.GetHighByte(n) });
                    if (xt == null)
                    {
                        DanGuChunResult.Text = "血糖仪中胆固醇测量数据读取失败";
                    }
                    else
                    {
                        MedicalResult.DanGuChun = BytesOP.MakeShort(xt.Data[8], xt.Data[7]) / 38.66f;
                        bChange = true;
                        DanGuChunResult.Text = "胆固醇测量数据为： " + MedicalResult.DanGuChun.ToString() + " mmol/L   ";
                    }
                }
            }
            //}
            lDanGuChun.Text = "读取完成";
            xt = XueTangComProc(0x20, 0x0004, null);
            if (xt == null)
            {
                lDanGuChun.Text += "-------清除历史数据失败";
            }
            if (CP1616Packet.CP1616ComProc(ref SysConfig.XPCom, 0x03, 0x0001, 0x01) == null)
            {
                DanGuChunResult.Text = "与血糖仪建立连线失败，请检查连线";
                return;
            }
        }
        BeneCheckPacket XueTangComProc(ushort com, ushort Param, byte[] data)
        {
            BeneCheckPacket ret = new BeneCheckPacket(com);
            byte[] tx;
            if(data==null)
                tx= BeneCheckPacket.MakeBeneCheckPacket(com, Param);
            else
                tx = BeneCheckPacket.MakeBeneCheckPacket(com, Param,data);
            SysConfig.XueTangCom.Write(tx, 0, tx.Length);
            int retry=5;
            while (retry!=0)
            {
                while(true)
                {
                    try
                    {
                        if (ret.DataPacketed((byte)SysConfig.XueTangCom.ReadByte()))
                        {
                            return ret;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("血糖通信失败" + ex.Message);
                        break;
                    }
                }
                retry--;
            }
            return null;
        }
    }
    public class xtyData
    {
        //public DateTime dt;
        public float xt;
        public float xns;
        public float dgc;
    }
    /// <summary>
    /// 包头
    /// </summary>
    public class BeneCheckPacketHead
    {
        /// <summary>
        /// 包头大小
        /// </summary>
        public static Int32 HEAD_SIZE = 10;
        public ushort Command;
        public ushort Param;
        public ushort Len = 0;
        public byte[] Data;
        public BeneCheckPacketHead()
        {
            Data = new byte[HEAD_SIZE];
        }
    }
    public class BeneCheckPacket
    {
        public BeneCheckPacketHead Header;
        public byte[] Data;
        public int RxCount;
        public byte[] RxList;
        public ushort NeedCommand;
        public static Int32 BUFFER_SIZE = 256;
        public byte[] AllData;
        public BeneCheckPacket(ushort com)
        {
            NeedCommand = com;
            Header = new BeneCheckPacketHead();
            RxCount = 0;
            AllData = new byte[256];
        }
        public BeneCheckPacket()
        {
            NeedCommand = 0xffff;
            Header = new BeneCheckPacketHead();
            RxCount = 0;
            AllData = new byte[256];
        }
        public static byte[] MakeBeneCheckPacket(ushort com, ushort Param)
        {
            return MakeBeneCheckPacket(com, Param, null);
        }
        public static byte[] MakeBeneCheckPacket(ushort com, ushort Param,ushort Data)
        {
            return MakeBeneCheckPacket(com, Param, new byte[] { BytesOP.GetLowByte(Data), BytesOP.GetHighByte(Data) });
        }
        public static byte[] MakeBeneCheckPacket(ushort com, ushort Param, byte[] data)
        {
            byte[] txbuffer;
            if (data != null)
            {
                txbuffer = new byte[BeneCheckPacketHead.HEAD_SIZE + data.Length + 1];
                txbuffer[0] = 0x24;
                txbuffer[1] = 0x50;
                txbuffer[2] = 0x43;
                txbuffer[3] = 0x4c;
                txbuffer[4] = BytesOP.GetLowByte(com);
                txbuffer[5] = BytesOP.GetHighByte(com);
                txbuffer[6] = BytesOP.GetLowByte(Param);
                txbuffer[7] = BytesOP.GetHighByte(Param);
                txbuffer[8] = BytesOP.GetLowByte((ushort)data.Length);
                txbuffer[9] = BytesOP.GetHighByte((ushort)data.Length);
                for (int i = 0; i < data.Length; i++)
                {
                    txbuffer[i + BeneCheckPacketHead.HEAD_SIZE] = data[i];
                }
                txbuffer[BeneCheckPacketHead.HEAD_SIZE + data.Length] = Verify.GetVerify_byteSum(txbuffer, 1, txbuffer.Length - 2);
            }
            else
            {
                //24 50 43 4c 01 00 00 00 00 00 e0
                txbuffer = new byte[BeneCheckPacketHead.HEAD_SIZE + 1];
                txbuffer[0] = 0x24;
                txbuffer[1] = 0x50;
                txbuffer[2] = 0x43;
                txbuffer[3] = 0x4c;
                txbuffer[4] =BytesOP.GetLowByte(com);
                txbuffer[5] =BytesOP.GetHighByte(com);
                txbuffer[6] =BytesOP.GetLowByte(Param);
                txbuffer[7] =BytesOP.GetHighByte(Param);
                txbuffer[8] =00;
                txbuffer[9] =00;
                txbuffer[10] =Verify.GetVerify_byteSum(txbuffer,1,txbuffer.Length-2);
            }
            return txbuffer;
        }
        public bool DataPacketed(byte rx)
        {
            //判断读取的字节数+缓冲区已有字节数是否超过缓冲区总大小
            AllData[RxCount++] = rx;
            if (RxCount < (BeneCheckPacketHead.HEAD_SIZE + 1))
            {
                Header.Data[RxCount - 1] = rx;
                if (RxCount == 1)
                {
                    if (Header.Data[0] != 0x24)
                    {
                        RxCount = 0;
                    }
                }
                else if (RxCount == 2)
                {
                    if (Header.Data[1] != 0x50)
                    {
                        RxCount = 0;
                    }
                }
                else if (RxCount == 3)
                {
                    if (Header.Data[2] != 0x43)
                    {
                        RxCount = 0;
                    }
                }
                else if (RxCount == 4)
                {
                    if (Header.Data[3] != 0x4c)
                    {
                        RxCount = 0;
                    }
                }
                else if (RxCount == 6)
                {
                    Header.Command = BytesOP.MakeShort(Header.Data[5], Header.Data[4]);
                    if (NeedCommand != 0xffff)
                    {
                        if (Header.Command != NeedCommand)
                        {
                            RxCount = 0;
                        }
                    }
                }
                else if (RxCount == 8)
                {
                    Header.Param = BytesOP.MakeShort(Header.Data[7], Header.Data[6]);
                }
                else if (RxCount == 10)
                {
                    Header.Len = BytesOP.MakeShort(Header.Data[9],Header.Data[8]);
                    if (Header.Len != 0)
                        Data = new byte[Header.Len + 1];
                }
            }
            else
            {
                if (Header.Len != 0)
                {
                    Data[RxCount - BeneCheckPacketHead.HEAD_SIZE - 1] = rx;
                }
                if (RxCount == (BeneCheckPacketHead.HEAD_SIZE + Header.Len + 1))
                {
                    byte s1 = Verify.GetVerify_byteSum(AllData,1, RxCount - 2);
                    if (AllData[RxCount - 1] == s1)
                    {
                        return true;
                    }
                    else
                    {
                        RxCount = 0;
                        return false;
                    }
                }
            }
            return false;
        }
    }
}
